// memberVip/pages/memberPay/memberPay.js
var common = require("../../../common/common.js").common;

var util = require("../../../utils/util.js");

var {$author: $author} = require("../../../components/base/authorization.js");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        buttonClicked: false,
        chooseClass: 0,
        vip_price: "",
        //会员价格
        coupon_info: [],
        //赠送优惠券
        vipStatus: "",
        //会员状态
        ids: "",
        //会员套餐id
        yue: "",
        //余额
        shows: false,
        //余额支付弹窗是否显示
        payWayList: [ {
            iconfonts: "icon-yue",
            //支付方式icon
            payWayName: "余额",
            //支付方式名称
            isChecked: true,
            //radio状态
            color: "#FFAE00",
            //icon颜色,
            isDisabled: false
        }, {
            iconfonts: "icon-weixinzhifu",
            payWayName: "微信支付",
            isChecked: false,
            color: "#45C144",
            isDisabled: false
        } ],
        //支付方式
        subscribeMessage: true,
        tmplIds: []
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top
        });
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.getHeader();
        let that = this;
        that.getBase();
        that.getVipStatus();
        //获取会员状态信息
                that.getBalance().then(() => {
            that.getVipInfo();
            //获取会员套餐信息
                });
        //获取余额
                that.getData();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        let that = this;
        that.getVipStatus();
        //获取会员状态信息
                that.getBalance().then(() => {
            that.getVipInfo();
            //获取会员套餐信息
                });
        //获取余额
                that.getData();
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            data: {},
            success: res => {
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    apptitle: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    phone: res.extra.phone,
                    copyImg: res.extra.copyright_img,
                    l_supply: res.extra.l_supply,
                    rp_name: res.extra.rp_name,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    new_member_audit: res.extra.new_member_audit,
                    userAuditStatus: res.extra.userAuditStatus
                });
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
            }
        });
    },
    getVipStatus: function() {
        let that = this;
        common.request({
            endpoint: "vipcard/vip-verify",
            method: "POST",
            data: "",
            success: res => {
                that.setData({
                    vipStatus: res.extra.vip_card,
                    times: res.extra.end_date
                });
            }
        });
    },
    chooseClass: function(e) {
        let that = this;
        let chooseClass = e.currentTarget.dataset.id;
        that.setData({
            chooseClass: chooseClass,
            vip_price: e.currentTarget.dataset.price
        });
        let totale_price = e.currentTarget.dataset.price;
        let type = e.currentTarget.dataset.type;
        let payWayList = that.data.payWayList;
        let balanceNumTip;
        switch (type) {
          case "2":
            payWayList = [ {
                iconfonts: "icon-yue",
                //支付方式icon
                payWayName: "余额",
                //支付方式名称
                isChecked: true,
                //radio状态
                color: "#FFAE00",
                //icon颜色,
                isDisabled: false
            } ];
            break;

          case "1":
            payWayList = [ {
                iconfonts: "icon-weixinzhifu",
                payWayName: "微信支付",
                isChecked: false,
                color: "#45C144",
                isDisabled: false
            } ];
            break;

          case "3":
            payWayList = [ {
                iconfonts: "icon-yue",
                //支付方式icon
                payWayName: "余额",
                //支付方式名称
                isChecked: true,
                //radio状态
                color: "#FFAE00",
                //icon颜色,
                isDisabled: false
            }, {
                iconfonts: "icon-weixinzhifu",
                payWayName: "微信支付",
                isChecked: false,
                color: "#45C144",
                isDisabled: false
            } ];
        }
        if (parseFloat(totale_price) <= parseFloat(that.data.balanceNum) && (type == 2 || type == 3)) {
            //余额足够支付
            payWayList.forEach((item, index) => {
                if (item.payWayName == "余额") {
                    item.isDisabled = false;
                    item.isChecked = true;
                } else {
                    item.isDisabled = false;
                    item.isChecked = false;
                }
            });
            balanceNumTip = "（余额：￥" + that.data.balanceNum + "）";
        } else {
            //余额不足
            console.log("余额不足");
            payWayList.forEach((item, index) => {
                if (item.payWayName == "余额") {
                    item.isDisabled = true;
                    item.isChecked = false;
                } else {
                    item.isDisabled = false;
                    item.isChecked = true;
                }
            });
            balanceNumTip = "（余额不足：￥" + that.data.balanceNum + "）";
        }
        that.setData({
            payWayList: payWayList,
            balanceNumTip: balanceNumTip
        });
        that.setData({
            payWayList: payWayList,
            //支付方式
            chooseClass: e.currentTarget.dataset.id,
            vip_price: e.currentTarget.dataset.price,
            coupon_info: e.currentTarget.dataset.coupon_info
        });
    },
    radioChange(e) {
        console.log(e);
        var data = this.data.payWayList;
        data.forEach((item, index) => {
            if (index == e.detail.value) {
                item.isChecked = true;
            } else {
                item.isChecked = false;
            }
        });
        this.setData({
            payWayList: data
        });
    },
    // 套餐渲染
    getVipInfo: function() {
        var that = this;
        common.request({
            endpoint: "vipcard/vip-info",
            method: "POST",
            data: {},
            success: res => {
                that.setData({
                    vipMethods: res.extra.vip_info
                });
                let type = that.data.vipMethods[0].buy_type;
                let payWayList = that.data.payWayList;
                let totale_price = parseFloat(that.data.vipMethods[0].price);
                let balanceNumTip;
                switch (type) {
                  case 2:
                    payWayList = [ {
                        iconfonts: "icon-yue",
                        //支付方式icon
                        payWayName: "余额",
                        //支付方式名称
                        isChecked: true,
                        //radio状态
                        color: "#FFAE00",
                        //icon颜色,
                        isDisabled: false
                    } ];
                    break;

                  case 1:
                    payWayList = [ {
                        iconfonts: "icon-weixinzhifu",
                        payWayName: "微信支付",
                        isChecked: false,
                        color: "#45C144",
                        isDisabled: false
                    } ];
                    break;

                  case 3:
                    payWayList = [ {
                        iconfonts: "icon-yue",
                        //支付方式icon
                        payWayName: "余额",
                        //支付方式名称
                        isChecked: true,
                        //radio状态
                        color: "#FFAE00",
                        //icon颜色,
                        isDisabled: false
                    }, {
                        iconfonts: "icon-weixinzhifu",
                        payWayName: "微信支付",
                        isChecked: false,
                        color: "#45C144",
                        isDisabled: false
                    } ];
                }
                if (parseFloat(totale_price) <= parseFloat(that.data.balanceNum) && (type == 2 || type == 3)) {
                    //余额足够支付
                    payWayList.forEach((item, index) => {
                        if (item.payWayName == "余额") {
                            item.isDisabled = false;
                            item.isChecked = true;
                        } else {
                            item.isDisabled = false;
                            item.isChecked = false;
                        }
                    });
                    balanceNumTip = "（余额：￥" + that.data.balanceNum + "）";
                } else {
                    //余额不足
                    console.log("余额不足");
                    payWayList.forEach((item, index) => {
                        if (item.payWayName == "余额") {
                            item.isDisabled = true;
                            item.isChecked = false;
                        } else {
                            item.isDisabled = false;
                            item.isChecked = true;
                        }
                    });
                    balanceNumTip = "（余额不足：￥" + that.data.balanceNum + "）";
                }
                that.setData({
                    payWayList: payWayList,
                    balanceNumTip: balanceNumTip
                });
                that.setData({
                    payWayList: payWayList,
                    //支付方式
                    chooseClass: that.data.vipMethods[0].id,
                    vip_price: that.data.vipMethods[0].price,
                    coupon_info: that.data.vipMethods[0].coupon_info
                });
            },
            fail() {}
        });
    },
    isCanUseBalance(totalPrice, balanceIsOpen) {
        var that = this;
        var payWayList = that.data.payWayList;
    },
    getData: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "My/myinfo/myinfo",
            method: "post",
            data: {
                openid: openid
            },
            success: res => {
                that.setData({
                    info: res.extra,
                    platStatus: res.extra.uni_mem
                });
            }
        });
    },
    //余额金额
    getBalance() {
        var that = this;
        return new Promise(function(resolve, reject) {
            common.request({
                endpoint: "Balance/balance/mybalance",
                method: "post",
                data: {},
                success(res) {
                    console.log(res, "balance");
                    that.setData({
                        balanceNum: res.extra.balance,
                        balanceNumTip: "（余额：￥" + res.extra.balance + "）"
                    });
                    resolve();
                },
                fail(err) {
                    console.log(err);
                    reject(err);
                }
            });
        });
    },
    // 立即开通
    kaitong() {
        var that = this;
        var payWayList = that.data.payWayList;
        var platway;
        common.getUserInfoNew({
            success() {
                payWayList.forEach((item, index) => {
                    if (item.isChecked) {
                        if (item.payWayName == "余额") {
                            platway = 2;
                            that.setData({
                                shows: !that.data.shows,
                                platway: platway
                            });
                        } else if (item.payWayName == "微信支付") {
                            platway = 1;
                            that.setData({
                                platway: platway
                            });
                        }
                    }
                });
                if (that.data.platway != 1 && that.data.platway != 2) {
                    wx.showModal({
                        title: "提示！",
                        content: "暂无支付方式或余额不足！"
                    });
                    return;
                }
                console.log("platway", that.data.platway);
                console.log("chooseClass", that.data.chooseClass);
                common.request({
                    endpoint: "vipcard/pay",
                    method: "POST",
                    data: {
                        vip_id: that.data.chooseClass,
                        buy_type: that.data.platway
                    },
                    success: res => {
                        console.log(res);
                        if (that.data.platway == 1) {
                            that.payOrder(res.extra, res.extra.order_id);
                        } else {
                            that.setData({
                                order_id: res.extra.order_id,
                                total_fee: res.extra.total_fee
                            });
                        }
                    },
                    fail(res) {
                        wx.wx.showModal({
                            content: res.message,
                            showCancel: true,
                            title: "提示",
                            success: result => {},
                            fail: res => {},
                            complete: res => {}
                        });
                    }
                });
            }
        });
    },
    //微信支付
    payOrder(res, order_no) {
        wx.requestPayment({
            timeStamp: res.pay.timeStamp,
            nonceStr: res.pay.nonceStr,
            package: res.pay.package,
            signType: res.pay.signType,
            paySign: res.pay.paySign,
            success: function(res) {
                console.log(res);
                wx.showToast({
                    title: "支付成功",
                    icon: "success",
                    mask: true,
                    duration: 3e3,
                    success: function(res) {
                        wx.showToast({
                            title: "购买成功！",
                            icon: "success",
                            success: function() {
                                common.request({
                                    endpoint: "vipcard/sync-notify",
                                    method: "post",
                                    data: {
                                        out_trade_no: order_no
                                    },
                                    success: res => {
                                        setTimeout(function() {
                                            wx.reLaunch({
                                                url: "/memberVip/pages/memberOpen/memberOpen"
                                            });
                                        }, 500);
                                    },
                                    fail(err) {
                                        wx.showModal({
                                            title: "提示",
                                            content: err.message
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            },
            fail: function(res) {}
        });
    },
    kaitongs() {
        var that = this;
        var sh = that.data.shows;
        that.setData({
            shows: !sh
        });
    },
    // 只执行一次函数
    buttonClicked() {
        let that = this;
        that.setData({
            buttonClicked: true
        });
        setTimeout(function() {
            that.setData({
                buttonClicked: false
            });
        }, 500);
    },
    //余额 是否开通会员
    opend() {
        var that = this;
        that.buttonClicked();
        common.request({
            endpoint: "vipcard/sync-notify",
            method: "post",
            data: {
                out_trade_no: that.data.order_id,
                total_fee: that.data.total_fee
            },
            success: res => {
                that.setData({
                    shows: !that.data.shows
                });
                setTimeout(function() {
                    wx.reLaunch({
                        url: "/memberVip/pages/memberOpen/memberOpen"
                    });
                }, 500);
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    }
});